<div class="layui-card">
	<div class="layui-card-header">
		<h2 class="header-title">角色管理</h2>
		<span class="layui-breadcrumb pull-right">
          <a href="#!console">首页</a>
          <a><cite>角色管理</cite></a>
        </span>
	</div>
	<div class="layui-card-body">
		<div class="layui-form toolbar">
			搜索：<input id="role-edit-search" class="layui-input search-input" type="text" placeholder="输入关键字" />&emsp;
			<button id="role-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
			<button id="role-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button> &emsp;

		</div>

		<!-- 数据表格 -->
		<table class="layui-table" id="role-table" lay-filter="role-table"></table>
	</div>
</div>

<!-- 表单弹窗 -->
<script type="text/html" id="role-model">
	<form id="role-form" lay-filter="role-form" class="layui-form model-form">
		<input name="userIdCreate" type="hidden" />
		<input name="roleId" type="hidden" />
		<div class="layui-form-item">
			<label class="layui-form-label">角色名称</label>
			<div class="layui-input-block">
				<input name="roleName" placeholder="请输入角色名" type="text" class="layui-input" maxlength="20" lay-verify="required" required/>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">角色标识</label>
			<div class="layui-input-block">
				<input name="roleSign" placeholder="多个用逗号分隔" type="text" class="layui-input" maxlength="20" lay-verify="required" required/>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">机构</label>
			<div class="layui-input-block">
				<select id="jgkey" name="orgId">
				</select>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">备注</label>
			<div class="layui-input-block">
				<textarea name="remark" placeholder="请输入内容" class="layui-textarea" maxlength="200"></textarea>
			</div>
		</div>
		<div class="layui-form-item model-form-footer">
			<button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
			<button class="layui-btn" lay-filter="role-form-submit" lay-submit>保存</button>
		</div>
	</form>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="qx-model">
	<form id="qx-form" lay-filter="qx-form" class="layui-form model-form">
		<input name="roleId" type="hidden" />
		<div class="layui-form-item">
			<div class="layui-input-block">
				<div id="LAY-auth-tree-index"></div>
			</div>
		</div>
		<div class="layui-form-item model-form-footer">
			<button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
			<button class="layui-btn" lay-filter="LAY-auth-tree-submit" lay-submit>保存</button>
		</div>
	</form>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="role-table-bar">
	<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
	<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="qxlb">权限</a>
</script>

<script>
	layui.use(['form', 'table', 'util', 'config', 'admin', 'formSelects', 'authtree'], function() {
		var form = layui.form;
		var table = layui.table;
		var config = layui.config;
		var layer = layui.layer;
		var util = layui.util;
		var admin = layui.admin;
		var authtree = layui.authtree;
		var formSelects = layui.formSelects;
		var alog = config.getTempData('loginInfo');
		showRoleList()

		function showRoleList() {
			$.ajax({
				type: "POST",
				url: path + '/sys/role/list1',
				data: {
					sortOrder: "asc",
					pageSize: 1000,
					pageNumber: 1,
					roleName: ''
				},
				dataType: "json",
				xhrFields: {
					withCredentials: true
				},
				beforeSend: function(request) {},
				success: function(data) {
					//渲染表格
					table.render({
						elem: '#role-table',
						data: data.rows,
						where: {
							access_token: config.getToken().access_token
						},
						page: false,
						cols: [
							[{
									field: 'roleId',
									title: '编号'
								},
								{
									field: 'roleName',
									title: '角色名称'
								},
								{
									field: 'orgName',
									title: '所属机构'
								},
								{
									field: 'remark',
									title: '备注'
								},
								{
									field: 'gmtCreate',
									templet: function(d) {
										return util.toDateString(d.gmtCreate);
									},
									title: '创建时间'
								},
								{
									align: 'center',
									toolbar: '#role-table-bar',
									title: '操作'
								}
							]
						]
					});

				},
				beforeSend: function() {},
				complete: function() {},

				error: function(result) {
					console.log(result);
				},
			})

		}

		// 添加按钮点击事件
		$('#role-btn-add').click(function() {
			showEditModel();
		});

		// 表单提交事件
		form.on('submit(role-form-submit)', function(data) {
			var hhh = $(".zbyjs .layui-layer-title").text();

			if(hhh == "添加角色") {
				jscz(roleSave, data.field);
			} else if(hhh == "修改角色") {
				jscz(roleUpdate, data.field);
			}
			return false;
		});

		function jscz(paths, datas) {
			$.ajax({
				type: "POST",
				url: paths,
				data: datas,
				dataType: "json",
				xhrFields: {
					withCredentials: true
				},
				success: function(data) {
					if(data.code == 0) {
						layer.closeAll();
						layer.msg(data.msg, {
							icon: 1
						});
						showRoleList()
					} else {
						layer.msg(data.msg, {
							icon: 2
						});
					}
				},
				complete: function() {},
				error: function(result) {
					console.log(result);
				},
			});
		}

		// 工具条点击事件
		table.on('tool(role-table)', function(obj) {
			var data = obj.data;
			if(obj.event === 'edit') { //修改
				showEditModel(data);
			} else if(obj.event === 'del') { //删除
				doDelete(obj);
			} else if(obj.event === 'qxlb') {
				console.log(data.roleId)
				roleq(data.roleId)
			}
		});

		// 搜索按钮点击事件
		$('#role-btn-search').click(function() {
			var keyword = $('#role-edit-search').val();
			table.reload('role-table', {
				where: {
					keyword: keyword
				}
			});
		});

		// 显示编辑弹窗
		var showEditModel = function(datas) {
			$.ajax({
				type: "POST",
				url: path + '/sys/org/list1',
				data: {
					sortOrder: "asc",
					pageSize: 1000,
					pageNumber: 1,
					roleName: ''

				},
				dataType: "json",
				xhrFields: {
					withCredentials: true
				},
				beforeSend: function(request) {},
				success: function(data) {
					layer.open({
						type: 1,
						title: datas ? '修改角色' : '添加角色',
						skin: 'zbyjs',
						area: '450px',
						offset: '120px',
						content: $('#role-model').html(),
						success: function() {
							$('#role-form')[0].reset();
							$('#role-form').attr('method', 'GET');
							var select = document.getElementById("jgkey")
							select.options.add(new Option("请选择", ''))
							for(var i = 0; i < data.length; i++) {
								select.options.add(new Option(data[i].name, data[i].orgId));
							}
							form.render(select);
							if(datas) {
								var j = {
									userIdCreate: alog.userId,
									roleName: datas.roleName,
									remark: datas.remark,
									roleSign: datas.roleSign,
									roleId: datas.roleId
								}
								$(select).val(datas.orgId);
								form.val('role-form', j);
								$('#role-form').attr('method', 'GET');
							}
						}
					});
					// 渲染多选下拉框

				},
				beforeSend: function() {},
				complete: function() {},

				error: function(result) {
					console.log(result);
				},
			})

		};

		// 删除
		var doDelete = function(obj) {
			layer.confirm('确定要删除吗？', function(i) {
				layer.close(i);
				layer.load(2);

				var x = []

				$.ajax({
					type: "POST",
					url: roleRemove,
					data: {
						id: obj.data.roleId
					},
					dataType: "json",
					xhrFields: {
						withCredentials: true
					},
					success: function(data) {
						console.log(data);
						if(data.code == 0) {
							layer.msg(data.msg, {
								icon: 1
							});
							layer.closeAll();
							showRoleList()
						} else {
							layer.msg(data.msg, {
								icon: 2
							});
						}
					},
					error: function(result) {
						console.log(result);
					},
				});
			});
		};

		function roleq(id) {

			$.ajax({
				type: "POST",
				url: roleqx,
				data: {
					id: id
				},
				dataType: "json",
				xhrFields: {
					withCredentials: true
				},
				beforeSend: function(request) {},
				success: function(data) {
					//渲染表格
					console.log(data)
					$.ajax({
						type: "POST",
						url: qxlist,
						data: {},
						//						async: false,
						dataType: "json",
						xhrFields: {
							withCredentials: true
						},
						success: function(datas) {
							console.log(datas)
							var sjc = data.rows.menuIdList;
							var yj = []
							layer.open({
								type: 1,
								title: "修改权限",
								skin: 'zbyjs',
								area: '450px',
								offset: '120px',
								content: $('#qx-model').html(),
								success: function() {
									$('#qx-form')[0].reset();
									$('#qx-form').attr('method', 'GET');
									for(var i = 0; i < datas.length; i++) {
										if(datas[i].parentId == 0) {
											var ej = []
											for(var j = 0; j < datas.length; j++) {
												if(datas[j].parentId == datas[i].menuId) {
													var sj = []
													for(var k = 0; k < datas.length; k++) {
														if(datas[k].parentId == datas[j].menuId) {
															sj.push({
																name: datas[k].name,
																value: datas[k].menuId,
																checked: false
															})
														}
													}
													ej.push({
														name: datas[j].name,
														value: datas[j].menuId,
														list: sj,
														checked: false
													})
												}
											}
											yj.push({
												name: datas[i].name,
												value: datas[i].menuId,
												checked: false,
												list: ej
											})
										}
									}
									for(var i = 0; i < yj.length; i++) {
										for(var j = 0; j < sjc.length; j++) {
											if(yj[i].value == sjc[j]) {
												yj[i].checked = true
											}
										}
										if(yj[i].list.length > 0) {
											for(var k = 0; k < yj[i].list.length; k++) {
												var erji = yj[i].list[k]
												for(var j = 0; j < sjc.length; j++) {
													if(erji.value == sjc[j]) {
														erji.checked = true
													}
												}
												if(erji.list.length > 0) {
													for(var y = 0; y < erji.list.length; y++) {
														for(var s = 0; s < sjc.length; s++) {
															if(erji.list[y].value == sjc[s]) {
																erji.list[y].checked = true
															}
														}
													}

												}
											}

										}
									}
									authtree.render('#LAY-auth-tree-index', yj, {
										inputname: 'authids[]',
										layfilter: 'lay-check-auth',
										// openall: true,
										autowidth: true,
									});
								}
							})

							// 使用 authtree.on() 不会有冒泡延迟
							form.on('submit(LAY-auth-tree-submit)', function(obj) {

								var checked = authtree.getChecked('#LAY-auth-tree-index');
								console.log('Choosed authids is', checked);
								

								$.ajax({
									type: "POST",
									url: roleqxxg,
									traditional:true,
									data: {
										roleId: id,
										menuIdList:checked
									},
									dataType: "json",
									xhrFields: {
										withCredentials: true
									},
									success: function(data) {
										console.log(data);
										if(data.code == 0) {
											
											layer.closeAll();
											layer.msg(data.msg, {
												icon: 1
											});
											showRoleList()
										} else {
											layer.msg(data.msg, {
												icon: 2
											});
										}
									},
									error: function(result) {
										console.log(result);
									},
								});

								return false;
							});

						},
						error: function(result) {
							console.log(result);
						}
					})

				},
				error: function(result) {
					console.log(result);
				},
			})

		}

	});
</script>